package cn.tac.test.base.reference;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tac
 * @since 20/10/2018
 */
public class SoftRef {
    /**
     * VM Options: -Xms5m -Xmx5m
     */
    public static void main(String[] args) throws InterruptedException {
        List<Foo> ls = new ArrayList<>();

        SoftReference<Foo> soft1 = new SoftReference<>(new Foo());
        System.out.println(soft1.get());
        oom(ls);
        System.out.println(soft1.get());

        SoftReference<Foo> soft2 = new SoftReference<>(new Foo());
        System.out.println(soft2.get());
        System.gc();
        System.out.println(soft2.get());
    }

    protected static void oom(List<Foo> ls) {
        try {
            while (true) {
                ls.add(new Foo());
            }
        } catch (OutOfMemoryError e) {
            System.out.println("out of memory: " + e.getMessage());
        }
    }

    private static class Foo {

    }
}
